<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>用药提醒</span>
        <div class="header-actions">
          <el-input
              v-model="searchQuery"
              placeholder="搜索药品名称"
              clearable
              style="width: 200px; margin-right: 10px"
              @clear="handleSearchClear"
              @keyup.enter="handleSearch"
          />
          <el-button @click="handleSearch">搜索</el-button>
          <el-button type="primary" @click="showAddMedicationDialog = true">
            <el-icon><Plus /></el-icon>添加提醒
          </el-button>
        </div>
      </div>
    </template>

    <el-empty v-if="medications.length === 0 && !loading" description="暂无用药提醒" />
    <el-skeleton v-if="loading" :rows="5" animated />

    <el-table
        v-else
        :data="filteredMedications"
        style="width: 100%"
        v-loading="loading"
        :default-sort="{ prop: 'startDate', order: 'descending' }"
        border
        stripe
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40" align="center" />
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column prop="medicationName" label="药品名称" width="120" sortable align="center" />
      <el-table-column prop="dosage" label="剂量" width="100" align="center" />
      <el-table-column label="状态" width="80" align="center">
        <template #default="{ row }">
          <el-tag
              size="small"
              :type="getStatusType(row)"
              :effect="getStatusEffect(row)"
          >
            {{ getStatusText(row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="提醒时间" width="110" sortable align="center">
        <template #default="{ row }">
          {{ formatTime(row.reminderTime) }}
        </template>
      </el-table-column>
      <el-table-column label="日期范围" width="200" sortable align="center">
        <template #default="{ row }">
          <div :class="{ 'expired-date': isExpired(row.endDate) }">
            {{ formatDate(row.startDate) }} 至 {{ formatDate(row.endDate) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="频率" width="80" align="center">
        <template #default="{ row }">
          {{ row.frequency }}
        </template>
      </el-table-column>
      <el-table-column label="提醒日" width="100" align="center">
        <template #default="{ row }">
          {{ row.reminderDays || '每日' }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" show-overflow-tooltip align="center" />
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="{ row }">
          <el-button
              size="small"
              @click="selectDetail(row)"
          >
            详情
          </el-button>
          <el-button
              size="small"
              type="primary"
              @click="editMedication(row)"
          >
            编辑
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(row.reminderId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 批量操作按钮 -->
    <div class="batch-actions" v-if="selectedMedications.length > 0">
      <el-button type="danger" @click="handleBatchDelete">
        批量删除 ({{ selectedMedications.length }})
      </el-button>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="loadMedications"
          @size-change="handleSizeChange"
      />
    </div>

    <!-- 添加/编辑用药提醒对话框 -->
    <el-dialog
        v-model="showAddMedicationDialog"
        :title="isEditMode ? '编辑用药提醒' : '添加用药提醒'"
        width="90%"
        @closed="handleDialogClose"
    >
      <el-form
          :model="newMedication"
          :rules="rules"
          ref="medicationForm"
          label-width="100px"
          label-position="top"
      >
        <el-form-item label="药品名称" prop="medicationName">
          <el-input
              v-model="newMedication.medicationName"
              placeholder="请输入药品名称"
          />
        </el-form-item>
        <el-form-item label="用药剂量" prop="dosage">
          <el-input
              v-model="newMedication.dosage"
              placeholder="例如：1片/次"
          />
        </el-form-item>
        <el-form-item label="用药频率" prop="frequency">
          <el-input
              v-model="newMedication.frequency"
              placeholder="例如：每日3次"
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker
                  v-model="newMedication.startDate"
                  type="date"
                  placeholder="选择开始日期"
                  value-format="YYYY-MM-DD"
                  :disabled-date="disabledStartDate"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker
                  v-model="newMedication.endDate"
                  type="date"
                  placeholder="选择结束日期"
                  value-format="YYYY-MM-DD"
                  :disabled-date="disabledEndDate"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="提醒时间" prop="reminderTime">
          <el-time-picker
              v-model="newMedication.reminderTime"
              placeholder="选择时间"
              format="HH:mm"
              value-format="HH:mm"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="提醒日期">
          <el-select
              v-model="selectedDays"
              multiple
              placeholder="请选择提醒日期"
              style="width: 100%"
          >
            <el-option
                v-for="day in weekDays"
                :key="day.value"
                :label="day.label"
                :value="day.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
              v-model="newMedication.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddMedicationDialog = false">取消</el-button>
        <el-button type="primary" @click="submitMedicationForm">
          {{ isEditMode ? '保存' : '添加' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 用药提醒详情对话框 -->
    <el-dialog
        v-model="showDetailDialog"
        title="用药提醒详情"
        width="50%"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="药品名称">{{ detail.medicationName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="用药剂量">{{ detail.dosage || '-' }}</el-descriptions-item>
        <el-descriptions-item label="用药频率">{{ detail.frequency || '-' }}</el-descriptions-item>
        <el-descriptions-item label="开始日期">{{ formatDate(detail.startDate) || '-' }}</el-descriptions-item>
        <el-descriptions-item label="结束日期">
          <span :class="{ 'expired-date': isExpired(detail.endDate) }">
            {{ formatDate(detail.endDate) || '-' }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="提醒时间">{{ formatTime(detail.reminderTime) || '-' }}</el-descriptions-item>
        <el-descriptions-item label="提醒日期">{{ detail.reminderDays || '每日' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag
              :type="getStatusType(detail)"
              :effect="getStatusEffect(detail)"
          >
            {{ getStatusText(detail) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注">{{ detail.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button type="primary" @click="showDetailDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import {ref, onMounted, computed} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import axios from 'axios'
import dayjs from 'dayjs'

const medications = ref([])
const loading = ref(false)
const showAddMedicationDialog = ref(false)
const showDetailDialog = ref(false)
const isEditMode = ref(false)
const currentEditId = ref(null)
const searchQuery = ref('')
const medicationForm = ref(null)
const detail = ref({})
const selectedMedications = ref([])

//获取用户信息
const userStr = localStorage.getItem('user');
const userData = JSON.parse(userStr);

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 表单数据
const newMedication = ref({
  medicationName: '',
  dosage: '',
  frequency: '',
  startDate: '',
  endDate: '',
  reminderTime: '',
  reminderDays: '',
  remark: '',
  isActive: 1
})

// 周选择
const weekDays = ref([
  {value: '周一', label: '周一'},
  {value: '周二', label: '周二'},
  {value: '周三', label: '周三'},
  {value: '周四', label: '周四'},
  {value: '周五', label: '周五'},
  {value: '周六', label: '周六'},
  {value: '周日', label: '周日'}
])
const selectedDays = ref([])

// 表单验证规则
const rules = {
  medicationName: [
    {required: true, message: '请输入药品名称', trigger: 'blur'},
    {max: 50, message: '长度不超过50个字符', trigger: 'blur'}
  ],
  dosage: [
    {required: true, message: '请输入用药剂量', trigger: 'blur'},
    {max: 20, message: '长度不超过20个字符', trigger: 'blur'}
  ],
  frequency: [
    {required: true, message: '请输入用药频率', trigger: 'blur'},
    {max: 20, message: '长度不超过20个字符', trigger: 'blur'}
  ],
  startDate: [
    {required: true, message: '请选择开始日期', trigger: 'change'}
  ],
  endDate: [
    {required: true, message: '请选择结束日期', trigger: 'change'}
  ],
  reminderTime: [
    {required: true, message: '请选择提醒时间', trigger: 'change'}
  ]
}

// 计算属性
const filteredMedications = computed(() => {
  if (!searchQuery.value) return medications.value
  return medications.value.filter(item =>
      item.medicationName.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 加载方法
const loadMedications = async () => {
  try {
    loading.value = true
    const response = await axios.get(BASE_URL+'/api/v1/elderly/medicineReminder', {
      params: {
        // elderlyUserId: getUser().userId,
        elderlyUserId: userData.user.userId,
        pageNum: currentPage.value,
        pageSize: pageSize.value
      }
    })

    if (response.data.code === 2000) {
      medications.value = response.data.data.list || response.data.data
      total.value = response.data.data.total || response.data.data.length || 0
    } else {
      ElMessage.error(response.data.message || '获取用药提醒列表失败')
    }
  } catch (error) {
    ElMessage.error('网络请求失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

const handleSelectionChange = (selection) => {
  selectedMedications.value = selection.map(item => item.reminderId)
}

const handleDelete = (reminderId) => {
  ElMessageBox.confirm('确定要删除这条用药提醒吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await axios.post(
          BASE_URL+'/api/v1/elderly/medicineReminder/delete',
          [reminderId],  // 直接传数组，如 [123]
          { headers: { 'Content-Type': 'application/json' } }
      )

      if (response.data.code === 2000) {
        ElMessage.success('删除成功')
        loadMedications()
      } else {
        ElMessage.error(response.data.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  }).catch(() => {
    // 用户点击了取消
  })
}

const handleBatchDelete = () => {
  if (selectedMedications.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  ElMessageBox.confirm(`确定要删除这${selectedMedications.value.length}条用药提醒吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await axios.post(
          BASE_URL+'/api/v1/elderly/medicineReminder/delete',
          selectedMedications.value,  // 直接传数组，如 [1, 2, 3]
          { headers: { 'Content-Type': 'application/json' } }
      )

      if (response.data.code === 2000) {
        ElMessage.success(`成功删除${selectedMedications.value.length}条用药提醒`)
        selectedMedications.value = []
        loadMedications()
      } else {
        ElMessage.error(response.data.message || '批量删除失败')
      }
    } catch (error) {
      ElMessage.error('批量删除失败: ' + error.message)
    }
  }).catch(() => {
    // 用户点击了取消
  })
}

const selectDetail = (row) => {
  detail.value = {...row}
  showDetailDialog.value = true
}

const editMedication = (med) => {
  isEditMode.value = true
  currentEditId.value = med.reminderId
  newMedication.value = {...med}

  // 处理提醒日期
  if (med.reminderDays) {
    selectedDays.value = med.reminderDays.split(',')
  } else {
    selectedDays.value = []
  }

  showAddMedicationDialog.value = true
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadMedications()
}

const handleSearch = () => {
  currentPage.value = 1
  loadMedications()
}

const handleSearchClear = () => {
  searchQuery.value = ''
  loadMedications()
}

const submitMedicationForm = async () => {
  try {
    await medicationForm.value.validate()

    // 处理提醒日期
    if (selectedDays.value.length > 0) {
      newMedication.value.reminderDays = selectedDays.value.join(',')
    } else {
      newMedication.value.reminderDays = ''
    }

    const payload = {
      ...newMedication.value,
      elderlyUserId: getUser().userId,
      familyUserId: getUser().userId
    }

    if (isEditMode.value) {
      await updateMedication(payload)
    } else {
      await addMedication(payload)
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const addMedication = async (payload) => {
  try {
    const response = await axios.post(BASE_URL+'/api/v1/elderly/medicineReminder/add', payload)

    if (response.data.code === 2000) {
      ElMessage.success('添加用药提醒成功')
      showAddMedicationDialog.value = false
      loadMedications()
      resetNewMedication()
    } else {
      ElMessage.error(response.data.message || '添加用药提醒失败')
    }
  } catch (error) {
    ElMessage.error('网络请求失败: ' + error.message)
  }
}

const updateMedication = async (payload) => {
  try {
    const response = await axios.post(BASE_URL+'/api/v1/elderly/medicineReminder/update', payload)
    if (response.data.code === 2000) {
      ElMessage.success('更新用药提醒成功')
      showAddMedicationDialog.value = false
      loadMedications()
      resetNewMedication()
    } else {
      ElMessage.error(response.data.message || '更新用药提醒失败')
    }
  } catch (error) {
    ElMessage.error('网络请求失败: ' + error.message)
  }
}

const resetNewMedication = () => {
  newMedication.value = {
    medicationName: '',
    dosage: '',
    frequency: '',
    startDate: '',
    endDate: '',
    reminderTime: '',
    reminderDays: '',
    remark: '',
    isActive: 1
  }
  selectedDays.value = []
  isEditMode.value = false
  currentEditId.value = null
}

const handleDialogClose = () => {
  medicationForm.value?.resetFields()
  resetNewMedication()
}

const formatTime = (time) => {
  if (!time) return ''
  return typeof time === 'string' ? time : time.format('HH:mm')
}

const formatDate = (date) => {
  if (!date) return ''
  return typeof date === 'string' ? date : dayjs(date).format('YYYY-MM-DD')
}

const isExpired = (endDate) => {
  if (!endDate) return false
  const today = dayjs().format('YYYY-MM-DD')
  return endDate < today
}

const getStatusType = (row) => {
  if (!row.isActive) return 'info'
  if (isExpired(row.endDate)) return 'warning'
  return 'success'
}

const getStatusEffect = (row) => {
  if (!row.isActive) return 'plain'
  if (isExpired(row.endDate)) return 'dark'
  return 'light'
}

const getStatusText = (row) => {
  if (!row.isActive) return '已停用'
  if (isExpired(row.endDate)) return '已过期'
  return '进行中'
}

const disabledStartDate = (time) => {
  if (newMedication.value.endDate) {
    return time > dayjs(newMedication.value.endDate).toDate()
  }
  return false
}

const disabledEndDate = (time) => {
  if (newMedication.value.startDate) {
    return time < dayjs(newMedication.value.startDate).toDate()
  }
  return false
}

onMounted(() => {
  loadMedications()
})
</script>

<style scoped>
/* 基础样式 */
:deep(.el-card),
:deep(.el-table),
:deep(.el-form),
:deep(.el-dialog) {
  font-size: 16px;
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  padding: 0 10px;
}

.card-header span {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 表格样式 */
:deep(.el-table th),
:deep(.el-table td) {
  text-align: center !important;
  vertical-align: middle !important;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: bold;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

/* 按钮样式 */
.el-table .el-button {
  margin: 2px;
  font-size: 14px;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 批量操作按钮样式 */
.batch-actions {
  margin-top: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  justify-content: flex-end;
}

/* 过期日期样式 */
.expired-date {
  color: #e6a23c;
  font-weight: bold;
}

/* 详情弹窗样式 */
:deep(.el-descriptions__header) {
  margin-bottom: 20px;
}

:deep(.el-descriptions__title) {
  font-size: 18px;
  font-weight: bold;
}

:deep(.el-descriptions__label) {
  width: 120px;
  font-weight: bold;
  background-color: #f5f7fa;
}

:deep(.el-descriptions__content) {
  padding-left: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .header-actions {
    width: 100%;
    flex-wrap: wrap;
  }

  .header-actions .el-input {
    width: 100%;
    margin-right: 0;
    margin-bottom: 10px;
  }

  :deep(.el-dialog) {
    width: 90% !important;
  }

  :deep(.el-descriptions__label),
  :deep(.el-descriptions__content) {
    font-size: 14px;
  }
}
</style>